﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Data.SqlClient;
using TarreOA.TarreOADAL;
using TarreOA.TarreOAModels;

namespace TarreOA.TarreOABLL
{
    public class Flow_WorkProcessData_Service
    {
        /// <summary>
        /// 根据工作编号查找此工作表单及数据
        /// </summary>
        /// <param name="work_id"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public StringBuilder FindFormDataModelByWorkId(int work_id, int step)
        {
            StringBuilder sbu = new StringBuilder();
            Flow_WorkProcessData_DAO pwpd_dao = new Flow_WorkProcessData_DAO();
            string sql = "";
            SqlConnection sqlConn = null;
            SqlDataReader sqlDr = null;
            try
            {
                sqlConn = SQLManager.GetConn();
                int flow_id = 0;
                sql = "select Flow_Forms.Form_Model as 表单模型, Flow_NewFlow.Id as 流程编号 from Flow_Forms, Flow_NewFlow where Flow_Forms.id = (select Flow_NewFlow.Form_Id"
                    + " from Flow_NewFlow where Flow_NewFlow.Id = (select Flow_NewWork.New_Flow_Id from Flow_NewWork where "
                    + "Flow_NewWork.id = " + work_id + "))"
                    + " and Flow_NewFlow.id = (select Flow_NewWork.New_Flow_Id from Flow_NewWork where Flow_NewWork.id = " + work_id + ")";
                sqlDr = pwpd_dao.ExecuteForSelect(sql, new Hashtable(), sqlConn);
                if (sqlDr != null && sqlDr.HasRows)
                {
                    sqlDr.Read();
                    sbu.Append((string)sqlDr["表单模型"]);
                    flow_id = (int)sqlDr["流程编号"];
                }
                sqlDr.Close();
                sqlDr.Dispose();
                List<string> datas = new List<string>();
                sql = "select att_Content as 表单数据 from Flow_WorkProcessData where New_Work_id = " + work_id;
                sqlDr = pwpd_dao.ExecuteForSelect(sql, new Hashtable(), sqlConn);
                if (sqlDr != null && sqlDr.HasRows)
                {
                    while (sqlDr.Read())
                    {
                        datas.Add(sqlDr["表单数据"] == DBNull.Value ? "" : (string)sqlDr["表单数据"]);
                    }
                }
                sqlDr.Close();
                sqlDr.Dispose();
                string[] inputs = null;
                sql = "select Flow_NewFlowStep.Prc_Inputs as 可写字段 from Flow_NewFlowStep where New_Flow_id = " + flow_id + " and sort_Id = " + step;
                sqlDr = pwpd_dao.ExecuteForSelect(sql, new Hashtable(), sqlConn);
                if (sqlDr != null && sqlDr.HasRows)
                {
                    sqlDr.Read();
                    if (sqlDr["可写字段"] != DBNull.Value)
                    {
                        inputs = ((string)sqlDr["可写字段"]).Split(',');
                    }
                }
                sqlDr.Close();
                sqlDr.Dispose();
                sbu = ToRepariModel(sbu, datas, inputs);
                sbu.Append("<input name='WR_ID' type='hidden' value='" + work_id + "' /><input name='ST_SO' type='hidden' value='" + step + "'/>");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (sqlDr != null)
                {
                    sqlDr.Close();
                    sqlDr.Dispose();
                }
                if (sqlConn != null && sqlConn.State == System.Data.ConnectionState.Open)
                {
                    sqlConn.Close();
                    sqlConn.Dispose();
                }
            }
            return sbu;
        }

        /// <summary>
        /// 重建表单模型
        /// </summary>
        /// <param name="sbu"></param>
        /// <param name="datas"></param>
        /// <param name="inputs"></param>
        /// <returns></returns>
        private StringBuilder ToRepariModel(StringBuilder sbu, List<string> datas, string[] inputs)
        {
            string model = sbu.ToString();
            //model = model.Replace(">", " >");
            if (model != null && !"".Equals(model))
            {
                Hashtable ht = new Hashtable();
                string[] mms = { "<INPUT title=", "<SELECT title=", "<TEXTAREA title=" };
                int start = 0;
                //找出表单中所有元素的title，并以(起始位置，title)的形式存入链表中
                for (int i = 0; i < mms.Length; i++)
                {
                    string type = "";
                    if ("<INPUT title=".Equals(mms[i]))
                    {
                        type = "input";
                    }
                    else if ("<SELECT title=".Equals(mms[i]))
                    {
                        type = "select";
                    }
                    else
                    {
                        type = "textarea";
                    }
                    while (true)
                    {
                        start = model.IndexOf(mms[i], start + 1);
                        if (start == -1)
                        {
                            break;
                        }
                        //string title = "";
                        //if ("selected".Equals(type))
                        //{
                        //    title = model.Substring(start + mms[i].Length, model.IndexOf(">", start + mms[i].Length) - (start + mms[i].Length));
                        //}
                        //else
                        //{
                        //    title = model.Substring(start + mms[i].Length, model.IndexOf(" ", start + mms[i].Length) - (start + mms[i].Length));
                        //}
                        string title = model.Substring(start + mms[i].Length, model.IndexOf(" ", start + mms[i].Length) - (start + mms[i].Length));
                        string[] title_type = { title, type };
                        ht.Add(start + mms[i].Length + title.Length + 1, title_type);
                    }
                }
                int[] starts = new int[ht.Count];
                int m = 0;
                //将所有元素的起始位置装入数组
                foreach (object key in ht.Keys)
                {
                    starts[m] = (int)key;
                    m++;
                }
                //冒泡排序数组元素，根据元素的起始位置从小到大依次排列-_-!!!
                for (int i = 0; i < starts.Length - 1; i++)
                {
                    for (int j = i + 1; j < starts.Length; j++)
                    {
                        if (starts[i] > starts[j])
                        {
                            int temp = starts[i];
                            starts[i] = starts[j];
                            starts[j] = temp;
                        }
                    }
                }
                if (datas.Count == starts.Length)
                {
                    int new_add = 0;
                    for (int i = 0; i < starts.Length; i++)
                    {
                        string[] title_type_temp = (string[])ht[starts[i]];
                        bool state = false;
                        for (int j = 0; j < inputs.Length; j++)
                        {
                            if (inputs[j] != null)
                            {
                                if (title_type_temp[0].Equals(inputs[j]))
                                {
                                    state = true;
                                }
                            }
                        }
                        string insert = "";
                        if (state == false)
                        {
                            if (title_type_temp[1].Equals("input"))
                            {
                                int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                string temp = sbu.ToString().Substring(0, end + 1);
                                string this_type = "";
                                int type_start = temp.IndexOf("type=", starts[i] + new_add);
                                if (type_start != -1)
                                {
                                    this_type = temp.Substring(type_start + "type=".Length, temp.IndexOf(" ", type_start + "type=".Length + 1)
                                        - (type_start + "type='".Length) + 1);
                                }
                                if ("checkbox".Equals(this_type))
                                {
                                    if ("on".Equals(datas[i]))
                                    {
                                        insert = " name='DATA_" + i + "' readonly checked onclick='this.checked=1;' style='background-color:#CCCCCC'";
                                    }
                                    else
                                    {
                                        insert = " name='DATA_" + i + "' readonly onclick='this.checked=0;' style='background-color:#CCCCCC'";
                                    }
                                    sbu.Insert(starts[i] + new_add, insert);
                                }
                                else
                                {
                                    insert = " name='DATA_" + i + "' readonly value='" + datas[i] + "' style='background-color:#CCCCCC'";
                                    sbu.Insert(starts[i] + new_add, insert);
                                }
                            }
                            else if (title_type_temp[1].Equals("textarea"))
                            {
                                insert = " name='DATA_" + i + "' readonly style='background-color:#CCCCCC'";
                                sbu.Insert(starts[i] + new_add, insert);
                                int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                new_add += datas[i].Length;
                                sbu.Insert(end + 1, datas[i]);
                            }
                            else if (title_type_temp[1].Equals("select"))
                            {
                                insert = " name='DATA_" + i + "' style='background-color:#CCCCCC'";
                                sbu.Insert(starts[i] + new_add, insert);
                                int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                string temp = sbu.ToString().Substring(end + 1, sbu.ToString().IndexOf("</SELECT>", starts[i] + new_add) - (end + 1));
                                string newc = "<option selected='selected'>" + datas[i] + "</option>";
                                new_add += (newc.Length - temp.Length);
                                sbu.Remove(end + 1, sbu.ToString().IndexOf("</SELECT>", starts[i]) - (end + 1));
                                sbu.Insert(end + 1, newc);
                            }
                        }
                        else
                        {
                            if (datas[i] != null && !"".Equals(datas[i]))
                            {
                                if (title_type_temp[1].Equals("input"))
                                {
                                    int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                    string temp = sbu.ToString().Substring(0, end + 1);
                                    string this_type = "";
                                    int type_start = temp.IndexOf("type=", starts[i] + new_add);
                                    if (type_start != -1)
                                    {
                                        this_type = temp.Substring(type_start + "type=".Length, temp.IndexOf(" ", type_start + "type=".Length + 1)
                                            - (type_start + "type='".Length) + 1);
                                    }
                                    if ("checkbox".Equals(this_type))
                                    {
                                        if ("on".Equals(datas[i]))
                                        {
                                            insert = " name='DATA_" + i + "' checked ";
                                        }
                                        else
                                        {
                                            insert = " name='DATA_" + i + "' ";
                                        }
                                        sbu.Insert(starts[i] + new_add, insert);
                                    }
                                    else
                                    {
                                        insert = " name='DATA_" + i + "' value='" + datas[i] + "'";
                                        sbu.Insert(starts[i] + new_add, insert);
                                    }
                                }
                                else if (title_type_temp[1].Equals("textarea"))
                                {
                                    insert = " name='DATA_" + i + "'";
                                    sbu.Insert(starts[i] + new_add, insert);
                                    int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                    new_add += datas[i].Length;
                                    sbu.Insert(end + 1, datas[i]);
                                }
                                else if (title_type_temp[1].Equals("select"))
                                {
                                    insert = " name='DATA_" + i + "'";
                                    sbu.Insert(starts[i] + new_add, insert);
                                    int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                    string temp = sbu.ToString().Substring(end + 1, sbu.ToString().IndexOf("</SELECT>", starts[i] + new_add) - (end + 1));
                                    StringBuilder new_temp = new StringBuilder();
                                    new_temp.Append(temp.Replace("selected='selected'", ""));
                                    string str1 = " selected='selected'";
                                    int value_start = new_temp.ToString().IndexOf(datas[i], end);
                                    int value_end = new_temp.ToString().IndexOf("'", value_start);
                                    new_temp.Insert(value_end + 1, str1);
                                    new_add += (new_temp.ToString().Length - temp.Length);
                                    sbu.Remove(end + 1, sbu.ToString().IndexOf("</SELECT>", starts[i]) - (end + 1));
                                    sbu.Insert(end + 1, new_temp.ToString());
                                }
                            }
                            else
                            {
                                insert = " name='DATA_" + i + "'";
                                sbu.Insert(starts[i] + new_add, insert);
                            }
                        }
                        new_add += insert.Length;
                    }
                }
                sbu.Append(" <input type='hidden' name='max' value='" + starts.Length + "' /> ");
            }
            return sbu;
        }

        /// <summary>
        /// 保存工作流中表单数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int SaveProcessData(string sql)
        {
            Flow_WorkProcess_DAO fwp_dao = new Flow_WorkProcess_DAO();
            return fwp_dao.UpdateWorkProcessInfo(sql, new Hashtable());
        }

        /// <summary>
        /// 根据工作编号查找当前工作的表单信息
        /// </summary>
        /// <param name="work_id"></param>
        /// <returns></returns>
        public StringBuilder FindWorkFormShow(int work_id)
        {
            StringBuilder sbu = new StringBuilder();
            string sql = "select Flow_Forms.Form_Model as 表单模型 from Flow_Forms where Flow_Forms.id = (select Flow_NewFlow.Form_Id "
                + "from Flow_NewFlow where Flow_NewFlow.Id = (select Flow_NewWork.New_Flow_Id   from Flow_NewWork   where Flow_NewWork.id = " + work_id + "))";
            Flow_WorkProcessData_DAO fwpd_dao = new Flow_WorkProcessData_DAO();
            SqlConnection sqlConn = null;
            List<string> datas = new List<string>();
            try
            {
                sqlConn = SQLManager.GetConn();
                SqlDataReader sqlDr = fwpd_dao.ExecuteForSelect(sql, new Hashtable(), sqlConn);
                if (sqlDr != null && sqlDr.HasRows)
                {
                    sqlDr.Read();
                    sbu.Append(sqlDr["表单模型"] == DBNull.Value ? "" : (string)sqlDr["表单模型"]);
                    sqlDr.Close();
                    sqlDr.Dispose();
                }
                sql = "select att_Content as 表单数据 from Flow_WorkProcessData where New_Work_id = " + work_id;
                sqlDr = fwpd_dao.ExecuteForSelect(sql, new Hashtable(), sqlConn);
                if (sqlDr != null && sqlDr.HasRows)
                {
                    while (sqlDr.Read())
                    {
                        datas.Add(sqlDr["表单数据"] == DBNull.Value ? "" : (string)sqlDr["表单数据"]);
                    }
                    sqlDr.Close();
                    sqlDr.Dispose();
                }
                string model = sbu.ToString();
                if (model != null && !"".Equals(model))
                {
                    Hashtable ht = new Hashtable();
                    string[] mms = { "<input title='", "<select title='", "<textarea title='" };
                    int start = 0;
                    //找出表单中所有元素的title，并以(起始位置，title)的形式存入链表中
                    for (int i = 0; i < mms.Length; i++)
                    {
                        string type = "";
                        if ("<input title='".Equals(mms[i]))
                        {
                            type = "input";
                        }
                        else if ("<select title='".Equals(mms[i]))
                        {
                            type = "select";
                        }
                        else
                        {
                            type = "textarea";
                        }
                        while (true)
                        {
                            start = model.IndexOf(mms[i], start + 1);
                            if (start == -1)
                            {
                                break;
                            }
                            string title = model.Substring(start + mms[i].Length, model.IndexOf("'", start + mms[i].Length) - (start + mms[i].Length));
                            string[] title_type = { title, type };
                            ht.Add(start + mms[i].Length + title.Length + 1, title_type);
                        }
                    }
                    int[] starts = new int[ht.Count];
                    int m = 0;
                    //将所有元素的起始位置装入数组
                    foreach (object key in ht.Keys)
                    {
                        starts[m] = (int)key;
                        m++;
                    }
                    //冒泡排序数组元素，根据元素的起始位置从小到大依次排列-_-!!!
                    for (int i = 0; i < starts.Length - 1; i++)
                    {
                        for (int j = i + 1; j < starts.Length; j++)
                        {
                            if (starts[i] > starts[j])
                            {
                                int temp = starts[i];
                                starts[i] = starts[j];
                                starts[j] = temp;
                            }
                        }
                    }
                    if (datas.Count == starts.Length)
                    {
                        int new_add = 0;
                        for (int i = 0; i < starts.Length; i++)
                        {
                            string[] title_type_temp = (string[])ht[starts[i]];
                            string insert = "";
                            if (title_type_temp[1].Equals("input"))
                            {
                                int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                string temp = sbu.ToString().Substring(0, end + 1);
                                string this_type = "";
                                int type_start = temp.IndexOf("type='", starts[i] + new_add);
                                if (type_start != -1)
                                {
                                    this_type = temp.Substring(type_start + "type='".Length, temp.IndexOf("'", type_start + "type='".Length + 1)
                                        - (type_start + "type='".Length) + 1);
                                }
                                if ("checkbox".Equals(this_type))
                                {
                                    if ("on".Equals(datas[i]))
                                    {
                                        insert = " name='DATA_" + i + "' readonly checked onclick='this.checked=1;' style='background-color:#CCCCCC'";
                                    }
                                    else
                                    {
                                        insert = " name='DATA_" + i + "' readonly onclick='this.checked=0;' style='background-color:#CCCCCC'";
                                    }
                                    sbu.Insert(starts[i] + new_add, insert);
                                }
                                else
                                {
                                    insert = " name='DATA_" + i + "' readonly value='" + datas[i] + "' style='background-color:#CCCCCC'";
                                    sbu.Insert(starts[i] + new_add, insert);
                                }
                            }
                            else if (title_type_temp[1].Equals("textarea"))
                            {
                                insert = " name='DATA_" + i + "' readonly style='background-color:#CCCCCC'";
                                sbu.Insert(starts[i] + new_add, insert);
                                int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                new_add += datas[i].Length;
                                sbu.Insert(end + 1, datas[i]);
                            }
                            else if (title_type_temp[1].Equals("select"))
                            {
                                insert = " name='DATA_" + i + "' style='background-color:#CCCCCC'";
                                sbu.Insert(starts[i] + new_add, insert);
                                int end = sbu.ToString().IndexOf(">", starts[i] + new_add);
                                string temp = sbu.ToString().Substring(end + 1, sbu.ToString().IndexOf("</select>", starts[i] + new_add) - (end + 1));
                                string newc = "<option selected='selected'>" + datas[i] + "</option>";
                                new_add += (newc.Length - temp.Length);
                                sbu.Remove(end + 1, sbu.ToString().IndexOf("</select>", starts[i]) - (end + 1));
                                sbu.Insert(end + 1, newc);
                            }
                            new_add += insert.Length;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (sqlConn != null && sqlConn.State == System.Data.ConnectionState.Open)
                {
                    sqlConn.Close();
                    sqlConn.Dispose();
                }
            }
            return sbu;
        }
    }
}
